package org.come.init;

import java.math.BigDecimal;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.nio.charset.Charset;
import java.io.OutputStream;
import java.io.InputStream;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.come.log.LanderJPanel;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import org.come.until.ZipUtils;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.net.URI;
import java.awt.Desktop;
import java.awt.Desktop;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.File;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;

public class Tool
{
    public static JSONObject StrintToJson(String str) {
        try {
            if (str.charAt(0) != '{') {
                str = str.substring(1);
            }
            final JSONObject jsonObject = new JSONObject(str);
            return jsonObject;
        }
        catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getWebCon(final String domain) {
        final StringBuffer sb = new StringBuffer();
        try {
            final URL url = new URL(domain);
            final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            in.close();
        }
        catch (Exception e) {
            return null;
        }
        return sb.toString();
    }

    public static String readToString(final String fileName) {
        final String encoding = "UTF-8";
        final File file = new File(fileName);
        final Long filelength = Long.valueOf(file.length());
        final byte[] filecontent = new byte[filelength.intValue()];
        try {
            final FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e2) {
            e2.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        }
        catch (UnsupportedEncodingException e3) {
            System.err.println("The OS does not support " + encoding);
            e3.printStackTrace();
            return null;
        }
    }

    public static void browse2(final String url) throws Exception {
        final Desktop desktop = Desktop.getDesktop();
        if (Desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)) {
            final URI uri = new URI(url);
            desktop.browse(uri);
        }
    }

    public static void loadJar(final String jarPath) {
        final File jarFile = new File(jarPath);
        Method method = null;
        try {
            method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        }
        catch (NoSuchMethodException | SecurityException e1) {
            e1.printStackTrace();
        }
        final boolean accessible = method.isAccessible();
        try {
            method.setAccessible(true);
            final URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
            final URL url = jarFile.toURI().toURL();
            method.invoke(classLoader, url);
        }
        catch (Exception e2) {
            e2.printStackTrace();
        }
        finally {
            method.setAccessible(accessible);
        }
    }

    public static void parsing(final JSONObject JSONArray, final String version) {
        try {
            final JSONArray JSONCommands = JSONArray.getJSONArray("commands");
            int i = 0;
            while (i < JSONCommands.length()) {
                try {
                    final String string = (String)JSONCommands.get(i);
                    parsingCommand(string, version);
                    try {
                        Thread.sleep(100L);
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                catch (JSONException e2) {
                    e2.printStackTrace();
                }
                ++i;
            }
            Tool.bggin=true;
        }
        catch (JSONException e3) {
            e3.printStackTrace();
        }
    }

    public static void parsingCommand(final String command, final String version) {
        final String[] args = command.split(" ");
        int i = 0;
        while (i < args.length) {
            args[i] = args[i].replace((CharSequence)"%p%", (CharSequence)(System.getProperty("user.dir") + "/update/UpdatePacks/" + version + "/")).replace((CharSequence)"%s%", (CharSequence)(System.getProperty("user.dir") + "/"));
            ++i;
        }
        try {
            final String s = args[0];
            int n = -1;
            switch (s.hashCode()) {
                case 3643: {
                    if (s.equals("rm")) {
                        n = 0;
                        break;
                    }
                    else {
                        break;
                    }
                }
                case 3497: {
                    if (s.equals("mv")) {
                        n = 1;
                        break;
                    }
                    else {
                        break;
                    }
                }
                case 1412865661: {
                    if (s.equals("mvToZip")) {
                        n = 2;
                        break;
                    }
                    else {
                        break;
                    }
                }
                case 286804402: {
                    if (s.equals("delZipFile")) {
                        n = 3;
                        break;
                    }
                    else {
                        break;
                    }
                }
                case 3181: {
                    if (s.equals("cp")) {
                        n = 4;
                        break;
                    }
                    else {
                        break;
                    }
                }
                case 103950895: {
                    if (s.equals("mkdir")) {
                        n = 5;
                        break;
                    }
                    else {
                        break;
                    }
                }
            }
            switch (n) {
                case 0: {
                    if (args.length > 1) {
                        System.gc();
                        Path folderPath = Paths.get(args[1]);
                        deleteFolderRecursively(folderPath);
                        break;
                    }
                    else {
                        break;
                    }
                }
                case 1: {
                    if (args.length > 2) {
                        final File file1 = new File(args[1]);
                        final File file2 = new File(args[2]);
                        if (args[2].endsWith("/")) {
                            final File file3 = new File(file2, file1.getName());
                            if (file3.exists()) {
                                file3.delete();
                            }
                            FileUtils.moveFileToDirectory(file1, file2, true);
                        }
                        else {
                            if (file2.exists()) {
                                file2.delete();
                            }
                            FileUtils.moveFile(new File(args[1]), file2);
                        }
                        break;
                    }
                    else {
                        break;
                    }
                }
                case 2: {
                    if (args.length > 2) {
                      //  ZipUtils.addFileToZip(args[1], args[2], "8DE38E0DA5740A31B4636FCE02E271B1");
                        break;
                    }
                    else {
                        break;
                    }
                }
                case 3: {
                    if (args.length > 2) {
                        if (args[2].endsWith("/")) {
                          //  ZipUtils.deleteFolder(args[2], args[1], "8DE38E0DA5740A31B4636FCE02E271B1");
                            break;
                        }
                        else {
                        //    ZipUtils.deleteFile(args[2], args[1], "8DE38E0DA5740A31B4636FCE02E271B1");
                            break;
                        }
                    }
                    else {
                        break;
                    }
                }
                case 4: {
                    if (args.length > 2) {
                        File old=new File(args[1]);
                        if (Equ(args[2], '/')) {
                            if (old.isDirectory()){
                                Path folderPath = Paths.get(args[1]);
                                List<Path> files = getFilesInFolder(folderPath);
                                for (Path path:files){
                                    FileUtils.copyFileToDirectory(new File(path.toString()), new File(args[2]), true);
                                }
                            }else
                                FileUtils.copyFileToDirectory(new File(args[1]), new File(args[2]), true);
                            break;
                        }
                        else {
                            FileUtils.copyFile(new File(args[1]), new File(args[2]));
                            break;
                        }
                    }
                    else {
                        break;
                    }
                }
                case 5: {
                    if (args.length > 1) {
                        FileUtils.forceMkdir(new File(args[1]));
                        break;
                    }
                    else {
                        break;
                    }
                }
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean Equ(final String str, final char ch) {
        return str.charAt(str.length() - 1) == ch;
    }

    public static void downloadHttpUrl(final String url, final String dir, final String fileName, final UpdateView updateView, final long length) {
        InputStream input = null;
        OutputStream output = null;
        try {
            final URL httpurl = new URL(url);
            final File dirfile = new File(dir);
            if (!dirfile.exists()) {
                dirfile.mkdirs();
            }
            final HttpURLConnection conn = (HttpURLConnection)httpurl.openConnection();
            long l=conn.getContentLength();
            input = conn.getInputStream();
            output = new FileOutputStream(dir + fileName);
            final byte[] buffer = new byte[4096];
            long count = 0L;
            double p = 0.0;
            int n;
            while (-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
                count += (long)n;
                p = (double)count * 1.0 / (double)l ;
                LanderJPanel.getProgress().setBounds(375, 423, (int)((double)(int)p * 6.5), 19);
               // LanderJPanel.getKais().setIcon(new ImageIcon("img/0244-FF5102FC (175).png"));
                LanderJPanel.getKais().setText("更新中");
                LanderJPanel.getProgressBg().setVisible(true);
                LanderJPanel.getProgress().setVisible(true);
                p= BigDecimal.valueOf(p*100).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                System.out.println(p);
            }
        }
        catch (Exception e2) {
            try {
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            }
            catch (NullPointerException | IOException e1) {
                e1.printStackTrace();
            }
            e2.printStackTrace();
        }
    }

    public static void run_cmd(final String strcmd) {
    }
    public static   boolean bggin=true;
    public static void unZip(final File srcFile, final String destDirPath) throws RuntimeException {
        System.out.println("开始解压");
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        else {
            ZipFile zipFile = null;
            try {
                try {
                    zipFile = new ZipFile(srcFile, Charset.forName("GBK"));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                final Enumeration<?> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    final ZipEntry entry = (ZipEntry)entries.nextElement();
                    if (entry.isDirectory()) {
                        final String dirPath = destDirPath + "/" + entry.getName();
                        final File dir = new File(dirPath);
                        dir.mkdirs();
                    }
                    else {
                        final File targetFile = new File(destDirPath + "/" + entry.getName());
                        if (!targetFile.getParentFile().exists()) {
                            targetFile.getParentFile().mkdirs();
                        }
                        targetFile.createNewFile();
                        final InputStream is = zipFile.getInputStream(entry);
                        final FileOutputStream fos = new FileOutputStream(targetFile);
                        final byte[] buf = new byte[1024000];
                        int len;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                        fos.close();
                        is.close();
                    }
                }
            }
            catch (Exception e) {
                throw new RuntimeException("unzip error from ZipUtils", (Throwable)e);
            }
            finally {
                if (zipFile != null) {
                    try {
                        zipFile.close();
                    }
                    catch (IOException e2) {
                        e2.printStackTrace();
                    }
                }
            }
            System.out.println("解压完毕");
            return;
        }

    }
    private static List<Path> getFilesInFolder(Path folderPath) {
        List<Path> files = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(folderPath)) {
            for (Path entry : stream) {
                if (Files.isRegularFile(entry)) {
                    files.add(entry);
                }
            }
        } catch (IOException e) {
            System.err.println("Error getting files in folder: " + e.getMessage());
        }
        return files;
    }
    private static void deleteFolderRecursively(Path path) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
            for (Path entry : stream) {
                if (Files.isRegularFile(entry)) {
                    try {
                        Files.delete(entry);
                        //System.out.println("Deleted file: " + entry.toString());
                    } catch (IOException e) {
                        System.err.println("Error deleting file: " + e.getMessage());
                    }
                } else if (Files.isDirectory(entry)) {
                    deleteFolderRecursively(entry);
                }
            }
        } catch (IOException e) {
            System.err.println("Error deleting folder: " + e.getMessage());
        }

        try {
            Files.delete(path);
            // System.out.println("Deleted folder: " + path.toString());
        } catch (IOException e) {
            System.err.println("Error deleting folder: " + e.getMessage());
        }
    }
}
